<?php
/**
 * @author moufer<moufer@163.com>
 * @copyright (c)2001-2011 Moufersoft
 * @website www.modoer.com
 */
class msm_sms_twilio extends msm_sms {

	protected $name = 'Twilio';
	protected $descrption = '支持多国家手机短信发送，访问地址 <a href="http://www.twilio.com/" target="_blank">twilio.com</a>，<b>仅适用于UTF-8版本。</b>';

	private $sid = '';
	private $token = '';
	private $number = '';
	private $gateurl = '';

	private $country_code = '';

	public function __construct($config) 
	{
		parent::__construct($config);
		$this->set_account();
	}

	//发送短信息
	public function send($mobile, $message) 
	{
		if(!$mobile) redirect('手机不能为空');
		if(!$message) redirect('发送内容不能为空');

		if(substr($mobile, 0,1) != '+') {
			$mobile = $this->country_code.$mobile;
		}

		// this line loads the library
		try {
			require(MUDDER_ROOT.'api/third_party/twilio-php-master/Services/Twilio.php');

			$http = new Services_Twilio_TinyHttp(
				'https://api.twilio.com',
				array('curlopts' => array(
					CURLOPT_SSL_VERIFYPEER => false,
					//CURLOPT_SSL_VERIFYHOST => 2,
				))
			);

    			$client = new Services_Twilio($this->sid, $this->token, "2010-04-01", $http);
			//$client = new Services_Twilio($this->sid, $this->token); 
			$message = $client->account->messages->sendMessage(  
				$this->number,
				$mobile,
				$message
			);
		} catch (Exception $e) {
			$this->errorCode = $e->getCode();
			$this->errorMsg = $e->getMessage();
			$this->errorUrl = request_uri();
			$this->writeLog();
			if(defined('IN_ADMIN')) redirect($this->errorMsg);
			return false;
		}

		if($message->sid && strlen($message->sid) > 0) {
			return true;
		} else {
			return false;
		}
	
	}

	protected function create_from() 
	{
		$this->loader->helper('form');
		$elements = array();
		$elements[] =
			array(
			'title' => 'AccountSID',
			'des' => 'https://www.twilio.com/user/account/settings',
			'content' => form_input('twilio_sid', $this->config['twilio_sid'], 'txtbox2'),
		);
		$elements[] =
			array(
			'title' => 'AuthToken',
			'des' => '获取处同上',
			'content' => form_input('twilio_token', $this->config['twilio_token'], 'txtbox2'),
		);
		$elements[] =
			array(
			'title' => 'Twilio Number',
			'des' => '绑定手机号后生成的Twilio Number，格式例如：+14800000000（必须带加号），<a href="https://www.twilio.com/user/account/phone-numbers/incoming" target="_blank">登陆twilio可以在此处找到</a>',
			'content' => form_input('twilio_number', $this->config['twilio_number'], 'txtbox2'),
		);
		$elements[] =
			array(
			'title' => '默认手机国家编号',
			'des' => '如果准备发送的手机号没有提供国家编号（例如+86或+65等只能写1个编号；国家编号前必须有加号）
			<br />如果需要账号发送到各个国家的权限，<a href="https://www.twilio.com/user/account/settings/international" target="_blank">请在twilio里打开相应国家权限</a>，默认只打开twilio账号注册时所属国家）',
			'content' => form_input('twilio_country_code', $this->config['twilio_country_code'], 'txtbox2'),
		);
		return $elements;
	}

	protected function check_from() 
	{
		if(_G('charset')!='utf-8') redirect('对不起，本接口只能用于UTF-8编码。'); 
		$post = array();
		$post['twilio_sid'] = _post('twilio_sid',null,MF_TEXT);
		$post['twilio_token'] = _post('twilio_token',null,MF_TEXT);
		$post['twilio_number'] = _post('twilio_number',null,MF_TEXT);
		$post['twilio_country_code'] = _post('twilio_country_code',null,MF_TEXT);
		if(!$post['twilio_sid']) redirect('ACCOUNT SID 为空！');
		if(!$post['twilio_token']) redirect('AUTH TOKEN 为空！');
		if(!$post['twilio_number']) redirect('Twilio Number 为空！');
		return $post;
	}

	//设置短信帐号
	private function set_account() 
	{
		$this->sid = $this->config['twilio_sid'];
		$this->token = $this->config['twilio_token'];
		$this->number = $this->config['twilio_number'];
		$this->country_code = $this->config['twilio_country_code'];
	}

	//判断返回的短信息是否发送成功//一纬返回xml数据
	private function _return($value=null) 
	{
		$xml = simplexml_load_string($value);
		if ($xml->result >= 0) {
			return TRUE;
		} else {
			$this->errorCode = $xml->result;
			$this->errorMsg = $xml->message;
			return FALSE;
		}
	}
	
}

/* end */